import React, { useCallback, useEffect, useState } from "react";

import "./index.scss";

interface IProps {
  arr: Record<string, any>[];
  caption?: string;
  width?: number;
  formatters?: Record<string, (key: string, item: any) => any>;
  sortables?: string[];
  pageSize?: number;
  ref?: any;
  showActionColumn?: boolean;
  showSelection?: boolean;
}

enum SpecialColumn {
  COL_SELECTION = "COL_SELECTION",
  COL_ACTIONS = "COL_ACTIONS",
}

const StoTable: React.FC<IProps> = React.forwardRef(
  (
    {
      arr,
      caption,
      width,
      formatters,
      sortables,
      pageSize = 10,
      showSelection = true,
      showActionColumn: showActions = true,
    },
    ref
  ) => {
    /* ========== START ========== */

    const [asc, setAsc] = useState(true);

    const [currentPage, setCurrentPage] = useState(1);

    const [data, setData] = useState(
      arr.slice((currentPage - 1) * pageSize, currentPage * pageSize)
    );

    const [cols, setCols] = useState(Object.keys(data[0]));

    const sortDataByKey = useCallback(
      (key: string) => {
        if (sortables?.includes(key)) {
          console.log("asc=", asc);
          setAsc(!asc);

          arr = arr.sort((a, b) => {
            if (asc) {
              return Number(a[key] > b[key]) ? 1 : -1;
            } else {
              return Number(a[key] > b[key]) ? -1 : 1;
            }
          });

          setData([
            ...arr.slice((currentPage - 1) * pageSize, currentPage * pageSize),
          ]);
        }
      },
      [asc, currentPage, arr]
    );

    const updateData = () => {
      console.log("updateData!");
      setData([
        ...arr.slice((currentPage - 1) * pageSize, currentPage * pageSize),
      ]);
    };

    useEffect(() => {
      console.log("arr/currentPage changed!", arr, currentPage);
      updateData();
    }, [arr, currentPage]);

    useEffect(() => {
      console.log("STO：data changed!", data);
    }, [data]);

    const turnToPage = (page: number) => {
      console.log("turnToPage", page);
      setCurrentPage(page);
    };

    // 在组件内部定义暴露的API方法
    const doSomething = () => {
      console.log("Doing something...");
      // 执行一些操作
    };

    // 将暴露的API方法附加到ref上
    React.useImperativeHandle(ref, () => ({
      doSomething,
      turnToPage,
    }));

    return (
      <div
        className="sto-table-root"
        style={{ width: `${width ? width + "px" : "100%"}`, height: "100%" }}
      >
        <table>
          {caption && <caption>{caption}</caption>}

          <thead>
            <tr>
              {cols.map((key, index) => (
                <th
                  className={key === "id" ? "id-col" : ""}
                  key={index}
                  onClick={() => sortDataByKey(key)}
                >
                  {key}
                </th>
              ))}
            </tr>
          </thead>

          <tbody>
            {data.map((item) => (
              <tr key={item.id}>
                {Object.keys(item).map((key, i) => (
                  <td key={i}>
                    {formatters && formatters[key]
                      ? formatters[key](key, item)
                      : item![key]}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    );

    /* ========== END ========== */
  }
);

export default StoTable;
